package term

import (
	"context"
	"strconv"
	"strings"
	"time"

	"mall/common/globalkey"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/forum/model"
	"mall/service/forum/rpc/internal/svc"
	"mall/service/forum/rpc/internal/utils/errorhandler"
	"mall/service/forum/rpc/types/forum"

	"github.com/volatiletech/null/v8"
	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateTermLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateTermLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateTermLogic {
	return &UpdateTermLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateTermLogic) UpdateTerm(in *forum.TermInfo) (*forum.BaseResp, error) {
	// logx.Infof("UpdateTerm : %+v ", in)

	tx, err := l.svcCtx.DB.BeginTx(l.ctx, nil)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	if len(in.Ids) > 0 { // 批量修改状态
		now := time.Now()
		for _, id := range in.Ids {
			if id > 0 && in.Status != nil {
				term, err := l.svcCtx.ForumTerm.FindOneNoCache(l.ctx, tx, id)
				if err != nil {
					tx.Rollback()
					return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
				}

				term.Status = uint8(*in.Status)
				term.UpdatedAt = now
				err = l.svcCtx.ForumTerm.Update(l.ctx, tx, term, nil)
				if err != nil {
					tx.Rollback()
					return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
				}
			}
		}

		tx.Commit()

		return &forum.BaseResp{
			Msg: i18n.UpdateSuccess,
		}, nil
	}

	if in.Id == nil || *in.Id == 0 {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	if in.Name != nil && len(strings.TrimSpace(*in.Name)) == 0 {
		return nil, errorx.NewInvalidArgumentError("term.nameRequired")
	}

	id := *in.Id
	term, err := l.svcCtx.ForumTerm.FindOneNoCache(l.ctx, tx, id)
	if err != nil {
		tx.Rollback()
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	var skipMeta bool
	if in.SkipMeta != nil && *in.SkipMeta > 0 {
		skipMeta = true
	}
	var skipMedia bool
	if in.SkipMedia != nil && *in.SkipMedia > 0 {
		skipMedia = true
	}
	var skipContent bool
	if in.SkipContent != nil && *in.SkipContent > 0 {
		skipContent = true
	}

	if in.Name != nil {
		term.Name = strings.TrimSpace(*in.Name)

		filterMap := make(map[string]map[string][]any)
		filterMap[model.ForumTermColumns.Name] = map[string][]any{
			"equalTo": []any{term.Name},
		}
		filterMap[model.ForumTermColumns.Taxonomy] = map[string][]any{
			"equalTo": []any{term.Taxonomy},
		}
		list, _, err := l.svcCtx.ForumTerm.GetList(l.ctx, model.M{
			"pageSize": uint64(2),
			"select":   ",",
		}, -1, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		count := len(list)
		if count > 1 {
			return nil, errorx.NewAlreadyExistsError("term.nameAlreadyExists")
		}

		if count == 1 && list[0].TermID != id {
			return nil, errorx.NewAlreadyExistsError("term.nameAlreadyExists")
		}
	}

	if in.Slug != nil { // 允许为空，不管长度
		term.Slug = strings.TrimSpace(*in.Slug)
	}
	if in.ParentId != nil {
		term.ParentID = *in.ParentId
	}
	if in.GroupId != nil {
		term.TermGroup = *in.GroupId
	}
	if !skipContent {
		if in.Desc != nil {
			term.Description = *in.Desc
		}
		if in.FilteredDesc != nil {
			term.DescriptionFiltered = *in.FilteredDesc
		}
	}
	if in.Sort != nil {
		term.Sort = uint16(*in.Sort)
	}
	if in.Status != nil {
		term.Status = uint8(*in.Status)
	}
	term.UpdatedAt = time.Now()

	rel := &model.ForumTermRel{}
	if skipContent {
		rel.Blacklist = append(rel.Blacklist, model.ForumTermColumns.Description)
		rel.Blacklist = append(rel.Blacklist, model.ForumTermColumns.DescriptionFiltered)
	}

	var thumbnailIdMetaId uint64
	var thumbnailUrlMetaId uint64
	if !skipMeta {
		filterMap := make(map[string]map[string][]any)
		filterMap[model.ForumTermMetumColumns.TermID] = map[string][]any{
			"equalTo": []any{id},
		}
		list, _, err := l.svcCtx.ForumTerm.GetMeta(l.ctx, model.M{}, -1, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		if len(list) > 0 { // 原有的 Meta（决定现有的是增还是改）
			var omids []uint64
			oMetaMap := make(map[uint64]*model.ForumTermMetum)
			for _, v := range list {
				switch v.MetaKey { // 先排除特殊Key
				case "_thumbnail_id":
					thumbnailIdMetaId = v.MetaID
				case "_thumbnail_url":
					thumbnailUrlMetaId = v.MetaID
				default:
					omids = append(omids, v.MetaID)
					oMetaMap[v.MetaID] = v
				}
			}

			// 现有的 Meta（决定原有的是删还是留）
			nmidMap := make(map[uint64]struct{})
			if len(in.Meta) > 0 {
				for _, v := range in.Meta {
					if v.Key == nil || len(strings.TrimSpace(*v.Key)) == 0 {
						continue
					}

					if v.Value == nil || len(strings.TrimSpace(*v.Value)) == 0 {
						continue
					}

					var metum model.ForumTermMetum
					metum.TermID = id
					metum.MetaKey = strings.TrimSpace(*v.Key)
					metum.MetaValue = null.StringFrom(strings.TrimSpace(*v.Value))

					if v.Id != nil && *v.Id > 0 {
						if m, ok := oMetaMap[*v.Id]; ok { // 有值且是有效值，为修改，否则为新增
							nmidMap[*v.Id] = struct{}{} // 从删除中排除

							if m.MetaValue.Valid && m.MetaKey == metum.MetaKey && m.MetaValue.String == metum.MetaValue.String { // 不变，跳过
								continue
							}

							metum.MetaID = *v.Id
						}
					}

					rel.Meta = append(rel.Meta, &metum)
				}
			}

			for _, mid := range omids {
				if _, ok := nmidMap[mid]; !ok { // 当前不存在的值，应该删除
					rel.DelMetaIds = append(rel.DelMetaIds, mid)
				}
			}
		} else if len(in.Meta) > 0 { // 不存在原值，则都是新增
			for _, v := range in.Meta {
				if v.Key == nil || len(strings.TrimSpace(*v.Key)) == 0 {
					continue
				}

				if v.Value == nil || len(strings.TrimSpace(*v.Value)) == 0 {
					continue
				}

				var metum model.ForumTermMetum
				metum.TermID = id
				metum.MetaKey = strings.TrimSpace(*v.Key)
				metum.MetaValue = null.StringFrom(strings.TrimSpace(*v.Value))

				rel.Meta = append(rel.Meta, &metum)
			}
		}
	}

	if !skipMedia {
		filterMap := make(map[string]map[string][]any)
		filterMap[model.ForumAttachmentRelationshipColumns.ObjectID] = map[string][]any{
			"equalTo": []any{id},
		}
		filterMap[model.ForumAttachmentRelationshipColumns.ObjectType] = map[string][]any{
			"equalTo": []any{globalkey.ForumAttachmentTypeTag},
		}
		list, _, err := l.svcCtx.ForumTerm.GetMedia(l.ctx, model.M{}, -1, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		mediaUidMap := make(map[uint64]*model.ForumAttachmentRelationship)
		if len(list) > 0 {
			for _, v := range list {
				mediaUidMap[v.AttachmentRelationshipID] = v
			}
		}

		allMediaMap := make(map[string]string)
		exclusiveMap := make(map[string]string) // 防删除原有图文中的图片
		if len(in.AllMedia) > 0 {
			for _, v := range in.AllMedia {
				if v.Id != nil && v.Url != nil && len(*v.Id) > 0 && len(*v.Url) > 0 {
					allMediaMap[*v.Id] = *v.Url
					exclusiveMap[*v.Url] = *v.Id
				}
			}
		}

		if len(in.NewMedia) > 0 {
			var thumbnailOrder uint
			var thumbnailId uint64
			var thumbnailUrl string
			for idx, v := range in.NewMedia {
				var url string
				if v.Url != nil && len(*v.Url) > 0 { // v.Uri  content版本（包含?id）  v.Url  url当前版本 | attachment当前版本
					url = *v.Url
				}
				var uri string
				if v.Uri != nil && len(*v.Uri) > 0 {
					uri = *v.Uri
					if len(url) == 0 {
						url = uri
					}
				}
				if len(url) == 0 {
					continue
				}

				var thumbnail uint8
				if v.Thumbnail != nil && *v.Thumbnail > 0 {
					thumbnail = uint8(*v.Thumbnail)
				}
				var order uint
				if v.Order != nil {
					order = uint(*v.Order)
				} else {
					order = uint(idx) + globalkey.AttachmentOrderOffset
				}
				var altText string
				if v.AltText != nil && len(*v.AltText) > 0 {
					altText = *v.AltText
				}
				var meta []string
				if v.Name != nil && len(*v.Name) > 0 {
					meta = append(meta, "filename:"+*v.Name)
					if len(altText) == 0 {
						altText = *v.Name
					}
				}
				if v.MetaData != nil && len(*v.MetaData) > 0 {
					meta = append(meta, *v.MetaData)
				}
				if v.MimeType != nil && len(*v.MimeType) > 0 {
					meta = append(meta, "mimeType:"+*v.MimeType)
				}
				metaData := strings.Join(meta, ";")

				var mediaId uint64
				if v.Id != nil && len(*v.Id) > 0 {
					if i, err := strconv.ParseInt(*v.Id, 10, 64); err == nil {
						mediaId = uint64(i)
					}
				}
				var uid uint64
				if v.Uid != nil && *v.Uid > 0 {
					uid = *v.Uid
				}

				if uid > 0 { // 原有缩略图
					if _, ok := mediaUidMap[uid]; ok { // 存在，修改，否则无效
						delete(mediaUidMap, uid)
						rel.Media = append(rel.Media, &model.ForumAttachmentRelationship{
							AttachmentRelationshipID: uid,
							AttachmentID:             mediaId,
							AttachmentThumbnail:      thumbnail,
							AttachmentOrder:          order,
							AttachmentImageURL:       url,
							AttachmentImageAlt:       altText,
							AttachmentImageMeta:      metaData,
						})
					}
					continue
				}

				media := &model.ForumAttachmentRelationship{
					AttachmentID:        mediaId,
					AttachmentThumbnail: thumbnail,
					AttachmentOrder:     order,
					AttachmentImageURL:  url,
					AttachmentImageAlt:  altText,
					AttachmentImageMeta: metaData,
				}

				if thumbnail == 0 && mediaId > 0 { // thumbnail == 0 不是缩略图， mediaId > 0 不是外链，获取图文uri
					if uri, ok := allMediaMap[*v.Id]; ok {
						media.AttachmentSource = uri
					}
				}

				rel.Media = append(rel.Media, media)
			}

			for _, v := range rel.Media {
				if v.AttachmentThumbnail > 0 && (len(thumbnailUrl) == 0 || thumbnailOrder > v.AttachmentOrder) { // thumbnailOrder尚未赋值，或当前值更小
					thumbnailOrder = v.AttachmentOrder
					thumbnailId = v.AttachmentID
					thumbnailUrl = v.AttachmentImageURL
				}
			}

			if len(thumbnailUrl) > 0 {
				rel.Meta = append(rel.Meta, &model.ForumTermMetum{
					MetaID:    thumbnailIdMetaId,
					MetaKey:   "_thumbnail_id",
					MetaValue: null.StringFrom(strconv.FormatInt(int64(thumbnailId), 10)),
				})
				rel.Meta = append(rel.Meta, &model.ForumTermMetum{
					MetaID:    thumbnailUrlMetaId,
					MetaKey:   "_thumbnail_url",
					MetaValue: null.StringFrom(thumbnailUrl),
				})
			}
		}

		for _, v := range mediaUidMap {
			// "https://www.scentrobe.com/proxy2/static/uploads/image/202411/019325cc-f0c4-7545-b201-bc36eabc4d63.jpg?49669"
			if _, ok := exclusiveMap[v.AttachmentSource]; ok { // 如果在图文中，保留一次
				delete(exclusiveMap, v.AttachmentSource)
				continue
			}

			rel.DelMediaIds = append(rel.DelMediaIds, v.AttachmentRelationshipID)
		}
	}

	err = l.svcCtx.ForumTerm.Update(l.ctx, tx, term, rel)
	if err != nil {
		tx.Rollback()
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	tx.Commit()

	return &forum.BaseResp{
		Msg: i18n.UpdateSuccess,
	}, nil
}
